<?php

namespace Home\Controller;

/**
 * Description of DealerController.class控制器实例
 *
 * @author zhangzhen
 * @date 2017-01-03
 */
class DealerController extends DealerParentController {

    protected function _initialize() {
        $this->validateUtil = new \Org\Util\Validate();
    }
    /**
     * @description  异步上传证件照
     * @modify zhangzhen 2017-01-03
     */
    public function upload() {
        $param = I('request.');
        $configName = isset($param['config']) ? $param['config'] : 'default';
        $config_info = C($configName);
        // 检测文件大小 
        $fileSizes = array_column($_FILES, 'size');
        foreach ($fileSizes as $fileSize) {
            if ($fileSize > $config_info['maxSize']) {
                returnJson(500, 511);
                return;
            }
        }
        unset($fileSize);

        $config = array(
            'maxSize' => $config_info['maxSize'],
            'rootPath' => $config_info['rootPath'],
            'savePath' => $config_info['savePath'],
            'exts' => $config_info['exts'],
            'subName' => array('date', 'Ymd'),
        );

        $upload = new \Think\Upload($config);
        $info = $upload->upload();
        if (!$info) {
            returnJson(500, 511, $upload->getError());
        }
        $filename = '/Uploads/' . $info['file']['savepath'] . $info['file']['savename'];
        returnJson(200, 200, array('filename' => $filename));
    }

    /**
     * @description 经销商开通申请
     * @modify zhangzhen 2017-01-03
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function apply() {
        $this->checkLogout();
        $params =  I('post.');
        $validateRule = array(
            //'mobile' => 'notnull,notempty,mobile',
            'name' => 'notnull,notempty,nameLength20',
            'idcard' => 'notnull,notempty',
            'idcardpath' => 'notnull,notempty',
        );
        //检查参数
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);

        //参数赋值
        $mobile = $params['mobile'];
        $name = $params['name'];
        $idcard = $params['idcard'];
        $idcardpath = $params['idcardpath'];
        $remark = $params['remark'];
        $areaCode = I('post.areaCode', '86', 'string');

        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        $dealerApplyLogic = A('Common/DealerApply', 'Logic');
        $dealerApplyLogic->apply($mobile, $name, $idcard, $idcardpath, $remark, $areaCode);
  
        returnJson(200, 200);
    }

    /**
     * @description 后端管理人员登录操作
     * @modify zhangzhen 2017-1-4
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function login() {
        $this->checkLogout();
        $mobile = I('post.mobile', '', 'string');
        $password = I('post.password', '', 'string');
        $areaCode = I('post.areaCode', '86', 'string');
        //检查参数
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        $dealerLoginLogic = A('Common/dealerLogin', 'Logic');
        $hashPassword = hash('sha256', $password);
        $dealerLogin = $dealerLoginLogic->login($mobile, $hashPassword, $areaCode);

        // 生成cookie信息
        $guid = guidv4_for_openssl();
        $now = time();
        $RsaEncrypt = new \Org\Util\RSAEncrypt();
        $userSSID = $RsaEncrypt->meizhuEncrypt($dealerLogin['id']);
        if (!$userSSID) {
            returnJson(500, 505);
        }
        $userSSPS = cookieDealerSSPS($dealerLogin['mobile'], $hashPassword, $now);
        cookie(C('COOKIE_SERVER_REMEMBER_DEALER_UUID'), $guid);
        cookie(C('COOKIE_SERVER_REMEMBER_DEALER_USSID'), $userSSID);
        cookie(C('COOKIE_SERVER_REMEMBER_DEALER_USSPS'), $userSSPS);
        cookie(C('COOKIE_SERVER_REMEMBER_DEALER_PSTM'), $now);


        //清除原有session数据
        session(null);
        // 存储基本信息到session
        session(C('DEALER_AREACODE'), $dealerLogin['areacode']);
        session(C('DEALER_ID'), $dealerLogin['id']);
        session(C('DEALER_NAME'), $dealerLogin['name']);
        session(C('DEALER_MOBILE'), $dealerLogin['mobile']);
        session(C('DEALER_HEAD'), $dealerLogin['headpath']);
        returnJson(200, 200, 'success');
    }

    /**
     * @description 更新账户密码
     * @modify zhangzhen 2017-01-04
     */
    public function updatePassword() {
        $oldPassword = I('post.oldPassword');
        $newPassword = I('post.newPassword');
        $vcode = I('post.vcode');
        $userId = getDealerId();
        //验证参数
        $this->ajaxValidateReturn($this->validateUtil, $oldPassword, "password");
        $this->ajaxValidateReturn($this->validateUtil, $newPassword, "password");
        $this->ajaxValidateReturn($this->validateUtil, $vcode, "vcode");
        //检查验证码
        if (!checkVcode($vcode)) {
            returnJson(403, 122);
        }
        //查询账户并验证原密码
        $dealerLoginModel = D('DealerLogin');
        $dealerLogin = $dealerLoginModel->getInfo($userId);
        if ($dealerLogin['password'] != hash('sha256', $oldPassword)) {
            returnJson(403, 102);
        }
        //更新用户密码
        $result = $dealerLoginModel->setPassword($userId, hash('sha256', $newPassword));
        if ($result == false) {
            returnJson(500, 509);
        }
        returnJson(200, 200);
    }

    /**
     * @description 更新账户名称
     * @modify songanwei 2016-01-04
     */
    public function updateUserInfo() {
        $name = I('post.name');
        $head = I('post.head');
        $userId = getDealerId();
        //验证参数
        $this->ajaxValidateReturn($this->validateUtil, $name, "nameLength20");
        //查询账号
        $dealerLoginLogic = A('Common/DealerLogin', 'Logic');

        $dealerLoginLogic->saveInfo($userId, $name, $head);
        //更新头像session
        session(C('DEALER_HEAD'), $head);
        session(C('DEALER_NAME'), $name);
        returnJson(200, 200);
    }

    /**
     * @description  账户安全 发送验证码到已绑定手机
     * @modify zhangzhen 2017-01-04
     */
    public function sendMobile() {
        // 检测60秒防刷
        $mobileSendTime = session(C('SERCURE_MOBILE_VCODE_TIME')) ? session(C('SERCURE_MOBILE_VCODE_TIME')) : 0;
        $result = time() - $mobileSendTime - 60;
        $userId = getDealerId();

        //可再次发送短信验证码
        if ($result > 0) {
            $dealerLoginModel = D('DealerLogin');
            $dealerLogin = $dealerLoginModel->getInfo($userId);
            $mobile = $dealerLogin['mobile'];
            $areacode = $dealerLogin['areacode'];
            $mobileVcode = getRandomNumber();

            //发送短信
            if ($areacode = '86') {
                $smsUtil = new \Org\Util\Sms();
                $result = $smsUtil->sendVocode($mobile, $mobileVcode);
            } else {
                $smsUtil = new \Org\Util\yunPian();
                $result = $smsUtil->sendVcode($areacode, $mobile, $mobileVcode);
            }

            if (!$result) {
                returnJson(403, 151, 'error');
            }
            //session保存验证码
            session(C('SERCURE_MOBILE_VCODE'), $mobileVcode);
            //session保存验证码发送时间
            session(C('SERCURE_MOBILE_VCODE_TIME'), time());
            //session保存验证码有效结束时间
            session(C('SERCURE_MOBILE_VCODE_END_TIME'), time() + C('SERCURE_MOBILE_VCODE_END_TIME_EFFECTIVE'));
            returnJson(200, 200, 'success');
        } else {
            returnJson(403, 107, 'error');
        }
    }


    /**
     * @description 验证手机短信验证码
     * @modify zhangzhen 2016-01-04
     */
    public function verifyWithMobile() {
        $param = I('post.');
        $mobileCode = $param['vcode'];
        // 校验验证码
        $this->ajaxValidateReturn($this->validateUtil, $mobileCode, 'vcode6');

        //获取验证码结束时间
        $mobileVcodeEndTime = session(C('SERCURE_MOBILE_VCODE_END_TIME'));
        //获取验证码
        $mobileVcode = session(C('SERCURE_MOBILE_VCODE'));
        // 与session内的效验码以及过期时间进行比对
        if (($mobileVcode != $mobileCode) || ($mobileVcodeEndTime <= time())) {
            returnJson(403, 120);
        }
        session(C('SERCURE_MOBILE_VCODE'), null);
        session(C('SERCURE_MOBILE_VCODE_TIME'), null);
        session(C('SERCURE_MOBILE_VCODE_END_TIME'), null);
        returnJson(200, 200);
    }


    /**
     * @description 发送新手机短信验证码
     * @modify zhangzhen 2017-01-04
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function sendMobileNew() {
        $mobile = I('post.mobile');
        $areaCode = I('post.areaCode', '86', 'string');
        //检查参数
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        $dealerLoginModel = D('DealerLogin');
        //检查手机号是否与之前手机号一样
        $userId = getDealerId();
        $dealerLogin = $dealerLoginModel->getInfo($userId);
        if ($dealerLogin['mobile'] == $mobile) {
            returnJson(403, 106);
        }
        //检查手机号是否已被注册
        $dealerLogin = $dealerLoginModel->getInfoByMobile($mobile, $areaCode);
        if ($dealerLogin) {
            returnJson(403, 105);
        }

        // 检测60秒防刷
        $mobileSendTime = session(C('SERCURE_MOBILE_NEW_VCODE_TIME')) ? session(C('SERCURE_MOBILE_NEW_VCODE_TIME')) : 0;
        $result = time() - $mobileSendTime - 60;


        //可再次发送短信验证码
        if ($result > 0) {
            $mobileVcode = getRandomNumber();
            //发送短信
            if ($areaCode == '86') {
                $smsUtil = new \Org\Util\Sms();
                $result = $smsUtil->sendVocode($mobile, $mobileVcode);
            } else {
                $yunPian = new \Org\Util\yunPian();
                $result = $yunPian->sendVcode($areaCode, $mobile, $mobileVcode);
            }

            if (!$result) {
                returnJson(403, 151, 'error');
            }

            //保存新手机号
            session(C('SERCURE_MOBILE_NEW'), $mobile);
            //session保存验证码
            session(C('SERCURE_MOBILE_NEW_VCODE'), $mobileVcode);
            //session保存验证码发送时间
            session(C('SERCURE_MOBILE_NEW_VCODE_TIME'), time());
            //session保存验证码有效结束时间
            session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'), time() + C('SERCURE_MOBILE_NEW_VCODE_END_TIME_EFFECTIVE'));
            returnJson(200, 200, 'success');
        } else {
            returnJson(403, 107, 'error');
        }
    }

    /**
     * @description 验证并更换新手机号
     * @modify zhangzhen 2017-01-04
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function verifyWithMobileNew() {
        $vcode = I('post.vcode');
        $mobile = I('post.mobile');
        $areaCode = I('post.areaCode', '86', 'string');
        //检查参数
        $this->ajaxValidateReturn($this->validateUtil, $vcode, 'vcode6');
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        $userId = getDealerId();
        //检查数据
        $mobileNew = session(C('SERCURE_MOBILE_NEW'));
        if (!$mobileNew) {
            returnJson(500, 501);
        }
        //获取验证码结束时间
        $mobileVcodeEndTime = session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'));
        //获取验证码
        $mobileVcode = session(C('SERCURE_MOBILE_NEW_VCODE'));
        //验证新的短信手机
        if (($mobileNew != $mobile) || ($vcode != $mobileVcode) || ($mobileVcodeEndTime <= time())) {
            returnJson(403, 120);
        }
        $dealerLoginModel = D('DealerLogin');
        //更换手机号
        $result = $dealerLoginModel->setMobile($userId, $mobileNew, $areaCode);
        if ($result == false) {
            returnJson(500, 509);
        }
        session(C('DEALER_AREACODE'),$areaCode);
        session(C('SERCURE_MOBILE_NEW_VCODE'), null);
        session(C('SERCURE_MOBILE_NEW_VCODE_TIME'), null);
        session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'), null);
        session(C('DEALER_MOBILE'),$mobileNew);
        returnJson(200, 200);
    }

    /**
     * @description 忘记密码 发送短信验证码
     * @modify zhangzhen 2016-1-4
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function sendCode() {
        $this->checkLogout();
        $mobile = I('post.mobile');
        $areaCode = I('post.areaCode', '86', 'string');
        //检查参数
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        //检查手机号是否已注册
        $dealerLoginModel = D('DealerLogin');
        $dealerLogin = $dealerLoginModel->getInfoByMobile($mobile, $areaCode);
        if (empty($dealerLogin)) {
            returnJson(403, 100);
        }
        //检查是否一分钟发送过
        $messageSendTime = session(C('RESET_PASSWORD_SEND_TIME'));
        if (!empty($messageSendTime) && !isOverMinute($messageSendTime, 1)) {
            returnJson(403, 107);
        }
        //发送短信验证码
        $token = getRandomNumber();
        $sessionId = session_id();
        session(C('RESET_PASSWORD_VCODE'), $token);
        session(C('RESET_PASSWORD_SEND_MOBILE'), $mobile);

        if ($areaCode == '86') {
            $messageSender = new \Org\Util\Sms();
            $messageSendResult = $messageSender->sendVocode($mobile, $token);
        } else {
            $yunPian = new \Org\Util\yunPian();
            $messageSendResult = $yunPian->sendVcode($areaCode, $mobile, $token);
        }

        if (empty($messageSendResult)) {
            returnJson(403, 151);
        }
        session(C('RESET_PASSWORD_SEND_TIME'), time());
        returnJson(200, 200, 'success');
    }


    /**
     * @description 检查短信验证码
     * @modify songanwei 2015-12-31
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function checkCode() {
        $this->checkLogout();
        $mobile = I('post.mobile');
        $code = I('post.vcode');
        $areaCode = I('post.areaCode', '86', 'string');

        $sessionMobile = session(C('RESET_PASSWORD_SEND_MOBILE'));
        $sessionCode = session(C('RESET_PASSWORD_VCODE'));
        $messageSendTime = session(C('RESET_PASSWORD_SEND_TIME'));
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        $this->ajaxValidateReturn($this->validateUtil, $code, "notnull,notempty,vcode6");

        // 验证session参数是否存在
        if (empty($sessionMobile) || empty($sessionCode) || empty($messageSendTime)) {
            returnJson(403, 122, 'error');
        }
        // 验证手机是否与session存的一致
        if ($mobile != $sessionMobile) {
            returnJson(403, 122);
        }
        // 校验短信验证码5分钟过期
        if (isOverMinute($messageSendTime)) {
            returnJson(403, 153);
        }
        // 校验码正误
        if ($code != $sessionCode) {
            returnJson(403, 120, 'error');
        }

        // 校验成功,发送链接跳转
        $sessionId = session_id();
        session(C('RESET_PASSWORD_VALIDATE_PASSWORD'), true);
        $url = '/resetPassworddealer.html?id=' . $sessionId . '&mobile=' . $mobile;
        returnJson(200, 200, $url);
    }

    /**
     * @description 重置密码
     * @modify songanwei 2015-12-31
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function resetPassword() {
        $this->checkLogout();
        $mobile = I('post.mobile');
        $password = I('post.password');
        $areaCode = I('post.areaCode', '86', 'string');

        // 检查session内校验结果
        $resetValidatePass = session(C('RESET_PASSWORD_VALIDATE_PASSWORD'));
        if (empty($resetValidatePass)) {
            returnJson(403, 123);
        }
        // 校验手机号格式
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        // 执行重置密码

        $dealerLoginModel = D('DealerLogin');
        //检查是否存在此用户
        $dealerLogin = $dealerLoginModel->getInfoByMobile($mobile, $areaCode);
        if (!$dealerLogin) {
            returnJson(200, 100);
        }

        $result = $dealerLoginModel->setPassword($dealerLogin['id'], hash('sha256', $password));
        if ($result == false) {
            returnJson(403, 123);
        }
        returnJson(200, 200, 'success');
    }
    

    /**
     * @description 检查用户是否已存在
     * @modify zhangzhen 2017-01-04
     */
    public function checkUserExist() {
        $params = I('post.');
        $dealerLoginModel = D('DealerLogin');
        $mobile = $params['mobile'];
        $areaCode = isset($params['areaCode']) ? $params['areaCode'] : '86';
        $dealerLogin = $dealerLoginModel->getInfoByMobile($mobile, $areaCode);
        if (!$adminLogin) {
            returnJson(403, 100);
        }
        returnJson(200, 200, array('name' => $adminLogin['name']));
    }

}
